package com.globallogic.webapp.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.globallogic.webapp.javaclasses.Users;

@WebServlet(description = "Check the loging in", urlPatterns = { "/CheckLogingIn" })
public class CheckLogingIn extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public CheckLogingIn() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String inputPassword = request.getParameter("password");
		Users users = new Users();
		StringBuilder sb = new StringBuilder();
		HttpSession session = request.getSession();
		RequestDispatcher dispatcher;
		if (users.getUsers().containsKey(login)) {
			if (users.md5(inputPassword).equals(users.getUsers().get(login))) {
				sb.append("Welcome <b>" + login + " !</b>");
				session.setAttribute("str", sb.toString());
				dispatcher = request.getRequestDispatcher("Personal.jsp");
				dispatcher.forward(request, response);
			}else{
				sb.append("Password is not correct!");
				sb.append("<br> <a href=\'index.jsp\'> Index Page</a>");
				session.setAttribute("str", sb.toString());
				dispatcher = request.getRequestDispatcher("Message.jsp");
				dispatcher.forward(request, response);
			}
		} else {
			sb.append("This login is not exist!");
			sb.append("<br> <a href=\'index.jsp\'> Login Page</a>");
			session.setAttribute("str", sb.toString());
			dispatcher = request.getRequestDispatcher("Message.jsp");
			dispatcher.forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

}
